﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using NHibernate;
using NHibernate.Linq;

using Common.Model;
using Common.Error;
using OpenAPI.Model.API;
using OpenAPI.IDAL.API;
using DBUtility;

namespace OpenAPI.NhiDAL.API
{
    public class MethodDAL : IMethod
    {

        #region 分类管理

        /// <summary>
        /// 新增分类
        /// </summary>
        /// <param name="category"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool AddCategory(MethodCategoryInfo category, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            MethodCategoryInfo exists_c = session.Query<MethodCategoryInfo>().SingleOrDefault(c => c.CATEGORY_CD == category.CATEGORY_CD);

            if (exists_c == null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        session.Save(category);
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch
                    {
                        trans.Rollback();

                        result_stat = false;
                        error = ErrorHelper.NewError("", "Database Error");
                    }
                }
            }
            else
            {
                result_stat = false;
                error = ErrorHelper.NewError("", "已存在此编码的分类");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// 更新分类
        /// </summary>
        /// <param name="category"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool ModifyCategory(MethodCategoryInfo category, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            MethodCategoryInfo exists_c = session.Query<MethodCategoryInfo>().SingleOrDefault(c => c.CATEGORY_CD == category.CATEGORY_CD);
            if (exists_c != null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        exists_c.CATEGORY_NAME = category.CATEGORY_NAME;
                        exists_c.CATEGORY_DESC = category.CATEGORY_DESC;
                        exists_c.CATEGORY_ORDER = category.CATEGORY_ORDER;

                        session.Update(exists_c);
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch
                    {
                        trans.Rollback();

                        result_stat = false;
                        error = ErrorHelper.NewError("", "Database Error");
                    }
                }
            }
            else
            {
                result_stat = false;
                error = ErrorHelper.NewError("", "不存在此编码的分类");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="category_cd"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool DeleteCategory(string category_cd, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            MethodCategoryInfo exists_c = session.Query<MethodCategoryInfo>().SingleOrDefault(c => c.CATEGORY_CD == category_cd);
            if (exists_c != null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
//                        //删除方法所拥有的参数(SignArguments,UnSignArguments)
//                        session.Delete(@"from MethodSignArgumentInfo signArg 
//                                        where signArg.MethodSignArgumentPK.METHOD_NAME = ALL 
//                                            (select m.METHOD_NAME from MethodInfo m where m.CATEGORY_CD = ? )", category_cd, NHibernateUtil.String);
//                        session.Delete(@"from MethodUnSignArgumentInfo unSignArg 
//                                        where unSignArg.MethodUnSignArgumentPK.METHOD_NAME = ALL
//                                            (select m.METHOD_NAME from MethodInfo m where m.CATEGORY_CD = ? )", category_cd, NHibernateUtil.String);

//                        //删除ConsumerLevel中的Methods
//                        session.Delete(@"from MethodInConsumerLevelInfo lvl 
//                                        where lvl.MethodInConsumerLevelPK.METHOD_NAME = ALL
//                                            (select m.METHOD_NAME from MethodInfo m where m.CATEGORY_CD = ? )", category_cd, NHibernateUtil.String);


                        //批量删除方法
                        session.Delete("from MethodInfo m where m.CATEGORY_CD = ?", category_cd, NHibernateUtil.String);

                        //删除分类
                        session.Delete(exists_c);

                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch
                    {
                        trans.Rollback();

                        result_stat = false;
                        error = ErrorHelper.NewError("", "Database Error");
                    }
                }
            }
            else
            {
                result_stat = false;
                error = ErrorHelper.NewError("", "不存在此编码的分类");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// 获取某个分类
        /// </summary>
        /// <param name="category_cd"></param>
        /// <returns></returns>
        public MethodCategoryInfo GetCategory(string category_cd)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            MethodCategoryInfo category = session.Query<MethodCategoryInfo>().SingleOrDefault(c => c.CATEGORY_CD == category_cd);
            NHibernateHelper.CloseSession();

            return category;
        }

        /// <summary>
        /// 获取分类列表
        /// </summary>
        /// <returns></returns>
        public IList<MethodCategoryInfo> GetCategories()
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            IList<MethodCategoryInfo> categories = (from c in session.Query<MethodCategoryInfo>()
                                                    select c).ToList();
            NHibernateHelper.CloseSession();

            return categories;
        }

        #endregion

        #region 方法管理

        /// <summary>
        /// Add Method
        /// </summary>
        /// <param name="method"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool Add(MethodInfo method, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            MethodInfo exists_m = session.Query<MethodInfo>().SingleOrDefault(m => m.METHOD_NAME == method.METHOD_NAME);
            if (exists_m == null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        session.Save(method);
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch
                    {
                        trans.Rollback();

                        result_stat = false;
                        error = ErrorHelper.NewError("", "Database Error");
                    }
                }
            }
            else
            {
                result_stat = false;
                error = ErrorHelper.NewError("", "Exists Method[" + method.METHOD_NAME + "]");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// Modify Method
        /// </summary>
        /// <param name="method"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool Mod(MethodInfo method, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            MethodInfo exists_m = session.Query<MethodInfo>().SingleOrDefault(m => m.METHOD_NAME == method.METHOD_NAME);
            if (exists_m != null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        exists_m.METHOD_TEXT = method.METHOD_TEXT;
                        exists_m.METHOD_DESC = method.METHOD_DESC;
                        exists_m.METHOD_RETURN = method.METHOD_RETURN;
                        exists_m.METHOD_ORDER = method.METHOD_ORDER;
                        exists_m.USED_YN = method.USED_YN;

                        session.Update(exists_m);
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch
                    {
                        trans.Commit();

                        result_stat = false;
                        error = ErrorHelper.NewError("", "Database Error");
                    }
                }
            }
            else
            {
                result_stat = false;
                error = ErrorHelper.NewError("", "Exists Method[" + method.METHOD_NAME + "]");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// delete method
        /// </summary>
        /// <param name="method_name"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool Delete(string method_name, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            MethodInfo exists_m = session.Query<MethodInfo>().SingleOrDefault(m => m.METHOD_NAME == method_name);
            if (exists_m != null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        //参数及Level中的Methods会自动删除，因为定义了关联，所以会自动删除

                        //删除方法
                        session.Delete(exists_m);

                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch
                    {
                        trans.Rollback();

                        result_stat = false;
                        error = ErrorHelper.NewError("", "Database Error");
                    }
                }
            }
            else
            {
                result_stat = false;
                error = ErrorHelper.NewError("", "Not Exists Method[" + method_name + "]");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// 获取API方法
        /// </summary>
        /// <param name="used_yn">是否使用：Y/N，如果传空值，则获取全部</param>
        /// <returns></returns>
        public IList<MethodInfo> GetMethods(string used_yn)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            IList<MethodInfo> methods = (from m in session.Query<MethodInfo>()
                                         select m).ToList();

            if (!string.IsNullOrEmpty(used_yn))
            {
                methods = methods.Where(m => m.USED_YN.ToString() == used_yn).ToList();
            }
            NHibernateHelper.CloseSession();

            return methods.OrderBy(m => m.METHOD_ORDER).ToList();
        }

        /// <summary>
        /// 获取API方法详情
        /// </summary>
        /// <param name="method_name"></param>
        /// <returns></returns>
        public MethodInfo GetMethod(string method_name)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            MethodInfo method = session.Query<MethodInfo>().SingleOrDefault(m => m.METHOD_NAME == method_name);
            NHibernateHelper.CloseSession();

            return method;
        }

        #endregion

        #region 参数管理

        /// <summary>
        /// 新增签名参数
        /// </summary>
        /// <param name="argument"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool AddSignArgument(MethodSignArgumentInfo argument, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            MethodSignArgumentInfo exists_a = session.Query<MethodSignArgumentInfo>().SingleOrDefault(
                a => a.MethodSignArgumentPK.METHOD_NAME == argument.MethodSignArgumentPK.METHOD_NAME
                    && a.MethodSignArgumentPK.ARGUMENT_NAME == argument.MethodSignArgumentPK.ARGUMENT_NAME);

            if (exists_a == null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        session.Save(argument);
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch
                    {
                        trans.Rollback();

                        result_stat = false;
                        error = ErrorHelper.NewError("", "Database Error");
                    }
                }
            }
            else
            {
                error = ErrorHelper.NewError("", "Exists Argument[" + argument.MethodSignArgumentPK.ARGUMENT_NAME + "]");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// 删除签名参数
        /// </summary>
        /// <param name="method_name"></param>
        /// <param name="argument_name"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool DeleteSignArgument(string method_name, string argument_name, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            MethodSignArgumentInfo exists_a = session.Query<MethodSignArgumentInfo>().SingleOrDefault(
                a => a.MethodSignArgumentPK.METHOD_NAME == method_name
                    && a.MethodSignArgumentPK.ARGUMENT_NAME == argument_name.ToLower());

            if (exists_a != null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        session.Delete(exists_a);
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch
                    {
                        trans.Rollback();

                        result_stat = false;
                        error = ErrorHelper.NewError("", "Database Error");
                    }
                }
            }
            else
            {
                error = ErrorHelper.NewError("", "Not Exists Argument[" + argument_name + "]");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }


        /// <summary>
        /// 新增非签名参数
        /// </summary>
        /// <param name="argument"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool AddUnSignArgument(MethodUnSignArgumentInfo argument, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            MethodUnSignArgumentInfo exists_a = session.Query<MethodUnSignArgumentInfo>().SingleOrDefault(
                a => a.MethodUnSignArgumentPK.METHOD_NAME == argument.MethodUnSignArgumentPK.METHOD_NAME
                    && a.MethodUnSignArgumentPK.ARGUMENT_NAME == argument.MethodUnSignArgumentPK.ARGUMENT_NAME);

            if (exists_a == null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        session.Save(argument);
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch
                    {
                        trans.Rollback();

                        result_stat = false;
                        error = ErrorHelper.NewError("", "Database Error");
                    }
                }
            }
            else
            {
                error = ErrorHelper.NewError("", "Exists Argument[" + argument.MethodUnSignArgumentPK.ARGUMENT_NAME + "]");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// 删除非签名参数
        /// </summary>
        /// <param name="method_name"></param>
        /// <param name="argument_name"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool DeleteUnSignArgument(string method_name, string argument_name, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            MethodUnSignArgumentInfo exists_a = session.Query<MethodUnSignArgumentInfo>().SingleOrDefault(
                a => a.MethodUnSignArgumentPK.METHOD_NAME == method_name
                    && a.MethodUnSignArgumentPK.ARGUMENT_NAME == argument_name.ToLower());

            if (exists_a != null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        session.Delete(exists_a);
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch
                    {
                        trans.Rollback();

                        result_stat = false;
                        error = ErrorHelper.NewError("", "Database Error");
                    }
                }
            }
            else
            {
                error = ErrorHelper.NewError("", "Not Exists Argument[" + argument_name + "]");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }



        /// <summary>
        /// 获取某个方法的参数（不需签名）
        /// </summary>
        /// <param name="api_method"></param>
        /// <returns></returns>
        public IList<MethodUnSignArgumentInfo> GetUnSignArguments(string api_method)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            IList<MethodUnSignArgumentInfo> arguments = (from a in session.Query<MethodUnSignArgumentInfo>()
                                                         where a.MethodUnSignArgumentPK.METHOD_NAME.ToLower() == api_method
                                                         select a).OrderBy(a => a.MethodUnSignArgumentPK.ARGUMENT_NAME).ToList();
            NHibernateHelper.CloseSession();

            return arguments;
        }

        /// <summary>
        /// 获取某个方法的参数（需签名）
        /// </summary>
        /// <param name="api_method"></param>
        /// <returns></returns>
        public IList<MethodSignArgumentInfo> GetSignArguments(string api_method)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            IList<MethodSignArgumentInfo> arguments = (from a in session.Query<MethodSignArgumentInfo>()
                                                       where a.MethodSignArgumentPK.METHOD_NAME.ToLower() == api_method
                                                       select a).OrderBy(a => a.MethodSignArgumentPK.ARGUMENT_NAME).ToList();
            NHibernateHelper.CloseSession();

            return arguments;
        }

        #endregion


    }//
}//
